<template>
    <div>
        <!-- 面包屑区域start -->
          <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
          </el-breadcrumb>
        <!-- 面包屑区域end -->

        <!-- 卡片视图区域start -->
          <el-card>
              <el-row>
                  <el-col :span="7">
                      <el-input placeholder="请输入内容" v-model="queryList.query" clearable @clear="getUserList">
                          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                      </el-input>
                  </el-col>
                  <el-col :span="4">
                      <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
                  </el-col>
              </el-row>
          </el-card>
        <!-- 卡片视图区域end -->

        <!-- 主体内容区域start -->
            <el-table  :data="userList" stripe  style="width: 100%" border>
                <el-table-column type="index" label="#" ></el-table-column>
                <el-table-column prop="username"  label="姓名"  width="80"></el-table-column>
                <el-table-column prop="email" label="邮箱地址"  width="180"></el-table-column>
                <el-table-column prop="mobile" label="手机号码" width="130"> </el-table-column>
                <el-table-column prop="role_name" label="角色"> </el-table-column>
                <el-table-column prop="mg_state" label="状态">
                    <template slot-scope=" scope ">
                <el-switch v-model="scope.row.mg_state"   active-color="#13ce66"  inactive-color="#ff4949" @change="userStateChange(scope.row)"></el-switch>
                </template>
                </el-table-column>
                <el-table-column  label="操作">
                    <template slot-scope="scope">
                        <!-- 修改 -->
                      <el-button type="primary" icon="el-icon-edit" circle @click="editUser(scope.row.id)"></el-button>
                        <!-- 角色 -->
                      <el-tooltip effect="dark" content="分配角色" placement="top" enterable>
                        <el-button type="warning" icon="el-icon-s-tools" circle @click="setRole(scope.row)"></el-button>
                        </el-tooltip>
                        <!-- 删除 -->
                      <el-button type="danger" icon="el-icon-delete" circle @click="removeUserById(scope.row.id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        <!-- 主体内容区域end -->
        <!-- 分页区域 start -->
         <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryList.pagenum"
            :page-sizes="[1, 2, 5, 12]"
            :page-size="queryList.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
            </el-pagination>
        <!-- 分页区域 end-->

        <!-- 添加用户start -->
          <el-dialog title="提示" :visible.sync="addDialogVisible"  width="50%" @close="addClose">

            <!-- 添加主体区域start -->
              <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
              <el-form-item label="用户名称" prop="username">
                  <el-input v-model="addForm.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                  <el-input v-model="addForm.password"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                  <el-input v-model="addForm.email"></el-input>
              </el-form-item>
              <el-form-item label="手机号码" prop="mobile">
                  <el-input v-model="addForm.mobile"></el-input>
              </el-form-item>
              </el-form>
            <!-- 添加主体区域end -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addUser">确 定</el-button>
                </span>
                </el-dialog>
        <!-- 添加用户end -->

        <!-- 修改用户start -->
            <el-dialog
                title="修改用户"
                :visible.sync="editVisible"
                width="50%" @close="editClose">
                <!-- 修改主体区域start -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" >
            <el-form-item label="用户名称" prop="username">
                <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="mobile">
                <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
            </el-form>
            <!-- 修改主体区域end -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editVisible = false" >取 消</el-button>
                    <el-button type="primary" @click="editsumint">确 定</el-button>
                </span>
                </el-dialog>
        <!-- 修改用户end -->

        <!-- 分配角色对话框start -->
            <el-dialog title="分配角色"  :visible.sync="RoleDialogVisible" width="50%">
            <div>
              <p>当前的用户:{{userinfo.username}}</p>
              <p>当前的角色:{{userinfo.role_name}}</p>
              <p>分配新角色:
                <el-select v-model="selectRoleId" placeholder="请选择">
                  <el-option  v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
                </el-select>
              </p>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="RoleDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
            </span>
          </el-dialog>
        <!-- 分配角色对话框end -->

    </div>
</template>

<script>
export default {

  data () {
    //   邮箱验证
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱'))
    }
    // 手机号验证
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号码'))
    }
    return {
      queryList: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前显示多少条数据
        pagesize: 2
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      editVisible: false,
      RoleDialogVisible: false,
      // 添加用户数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //   修改用户数据
      editForm: {},
      // 验证表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 需要被分配角色用户信息
      userinfo: {},
      // 所有角色数据的列表
      rolesList: [],
      selectRoleId: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryList })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (newSize) {
      this.queryList.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newNum) {
      this.queryList.pagenum = newNum
      this.getUserList()
    },
    async userStateChange (userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户失败')
      }
      this.$message.success('更新用户成功')
    },
    addClose () {
      this.$refs.addFormRef.resetFields()
    },
    addUser () {
      this.$refs.addFormRef.validate(async vali => {
        if (!vali) return
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    async editUser (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.editForm = res.data
      this.editVisible = true
    },
    editClose () {
      // 修改用户表单重置
      this.$refs.editFormRef.resetFields()
    },
    editsumint () {
      // 修改用户提交验证
      this.$refs.editFormRef.validate(async vali => {
        if (!vali) return
        const { data: res } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('修改信息失败')
        }
        this.editVisible = false
        this.getUserList()
        this.$message.success('修改信息成功')
      })
    },
    // 删除用户
    async removeUserById (id) {
      const removeUser = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeUser !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getUserList()
    },
    // 展示分配角色
    async setRole (userinfo) {
      this.userinfo = userinfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.rolesList = res.data
      this.RoleDialogVisible = true
    },
    // 点击确定按钮分配角色
    async saveRoleInfo () {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userinfo.id}/role`, { rid: this.selectRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败')
      }
      this.$message.success('更新角色成功')
      this.getUserList()
      this.RoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>

</style>
